<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use app\common\model\general\LihuaCity;
use app\common\model\general\LihuaStore;
use app\common\model\goods\LihuaCategory;
use app\common\model\goods\LihuaStock;
use think\Exception;
use think\Loader;
use think\Db;


/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class LihuaGoods extends Backend
{
    protected $cityLimit = true;
    protected $noNeedRight = ['enablestock', 'sel', 'selgoods'];

    /**
     * LihuaGoods模型对象
     * @var \app\common\model\goods\LihuaGoods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\goods\LihuaGoods;
        $this->view->assign("statusList", $this->model->getStatusList());
        $controllername = Loader::parseName($this->request->controller());
        if ($controllername == 'goods.lihua_goods') {
            $actionname = strtolower($this->request->action());
            if (in_array($actionname, ['add', 'edit'])) {
                $city_id = (int)$this->auth->city_id;
                if ($actionname == 'edit') {
                    $city_id = (int)$this->model->where('id', $this->request->param('ids'))->value('city_id');
                }
                $this->view->assign('cityArr', LihuaCity::getCityArr());
                $this->view->assign('categoryArr', LihuaCategory::getCityCategoryArr($city_id));
            }
        }
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            //更新所有城市在售的过期商品为下架
            $this->model->where('status', 1)
                ->where('sale_end', '<', date('Y-m-d H:i:s'))
                ->setField('status', 0);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['lihuacity', 'lihuacategory'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['lihuacity', 'lihuacategory'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('lihuacity')->visible(['name']);
                $row->getRelation('lihuacategory')->visible(['name']);
                $row['sale_time'] = $row['sale_start'].'~'.$row['sale_end'];
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);



            
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 启用禁用库存
     */
    public function enablestock($ids = 0)
    {
        if ($ids) {
            $where['id'] = $ids;
            if ($this->auth->city_id > 0) {
                $where['city_id'] = $this->auth->city_id;
            }

            $val = $this->model->where($where)->value('enable_stock');
            if ($val == '0') {
                $msg = '启用库存成功';
                $enable_stock = 1;
            } else {
                $msg = '禁用库存成功';
                $enable_stock = 0;
            }

            $this->model->where($where)->setField('enable_stock', $enable_stock);
            $this->success($msg, null, $enable_stock);
        }
        $this->error();
    }

    /**
     * 设置库存
     */
    public function stock($goods_id = 0, $city_id = 0)
    {
        if (!$goods_id || !$city_id) $this->error('参数错误');
        if ($this->auth->city_id > 0) $city_id = $this->auth->city_id;

        if ($this->request->isAjax()) {
            $store_id = (int)$this->request->post('store_id', 0);
            $stock_id = (int)$this->request->post('stock_id', 0);
            $num = $this->request->post('num');
            if (!$store_id) $this->error('参数错误');
            if ($num === '') $num = null;
            elseif (!is_numeric($num)) $this->error('参数错误');

            if ($stock_id > 0) {
                LihuaStock::where('id', $stock_id)->setField('num', $num);
            } else {
                try {
                    LihuaStock::create(['goods_id'=>$goods_id, 'store_id'=>$store_id, 'num'=>$num]);
                } catch (Exception $e) {
                    $this->error('唯一索引冲突');
                }
            }

            $this->success();
        }

        $list = LihuaStore::getCityStoreList($city_id);
        $arr  = LihuaStock::where('goods_id', $goods_id)->column('id,store_id,num', 'store_id');

        foreach ($list as $k => $v) {
            $list[$k]['stock_id'] = isset($arr[$v['id']]) ? $arr[$v['id']]['id'] : 0;
            $list[$k]['num'] = isset($arr[$v['id']]) ? $arr[$v['id']]['num'] : '';
        }

        $enable_stock = \app\common\model\goods\LihuaGoods::where('id', $goods_id)->value('enable_stock');
        $this->view->assign('enable_stock', $enable_stock);
        $this->view->assign('goods_id', $goods_id);
        $this->view->assign('list', $list);
        return $this->view->fetch();
    }


    /**
     * 选择商品
     *
     * @internal
     */
    public function sel()
    {
        $keyValue = $this->request->request("keyValue", "");
        $where = array('sale_end' => array('>=', date('Y-m-d H:i:s')));
        if($this->request->request("keyValue")){
            $where = array(
                'id' => array('in', explode(",", $keyValue)),
            );
        };
        if($this->auth->city_id>0) $where['city_id'] = $this->auth->city_id;
        $list = $this->model::where(['status'=>1, 'sale_end' => array('egt', date('Y-m-d H:i:s'))])
            ->where($where)
            ->select();
        return json(['list' => $list, 'total' => count($list)]);
    }

    /**
     * 红包选择商品
     *
     * @internal
     */
    public function selgoods()
    {
        $city_id = $this->request->request("city_id", "");
        $keyValue = $this->request->request("name", "");
        if(!$city_id) $this->error('请选择城市');
        $where = array('sale_start' => array('<=', date('Y-m-d H:i:s')));
        $where = array('sale_end' => array('>=', date('Y-m-d H:i:s')));
        if(!!$keyValue) $where = array('name' => array('like', "%".$keyValue."%"));
        if($city_id) $where['city_id'] = $city_id;
        $list = $this->model::where(['status'=>1, 'sale_end' => array('egt', date('Y-m-d H:i:s'))])
            ->where($where)
            ->select();
        return json(['list' => $list, 'total' => count($list)]);
    }

    /**
     * 复制操作
     */
    public function copy($ids = null)
    {

        $where['id'] = $ids;
        
        $city_id = 0;
        if ($this->cityLimit && !$this->auth->isSuperAdmin()) {
            $where[$this->cityLimitField] = $this->auth->city_id;
        }
        $row = $this->model->where($where)->find();
        if (!$row) $this->error('非法操作');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (!isset($params['city_id'])) {
                    $params['city_id'] = $this->auth->city_id;
                    $city_id = $this->auth->city_id;
                }else{
                    $city_id = $params['city_id'];
                };
                Db::startTrans();
                try {
                    $this->model->save($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign('cityArr', LihuaCity::getCityArr());
        $this->view->assign('categoryArr', LihuaCategory::getCityCategoryArr($city_id));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
